
/*
package.json里的
  "dependencies": {
    "@types/mysql": "^2.15.19",
    "better-sqlite3": "^8.2.0",
    "mysql": "^2.18.1"
  }
  被注释了
*/
import { Application, connector, createApp, Session } from "mydog";
let app = createApp();

import { getCpuUsage } from "./app/cpuUsage";
import { HallMgr } from "./app/hallMgr";
import { RoomMgr } from "./app/roomMgr";
//import { SqliteClient } from "./app/util/sqlite";

import { e_svrType } from "./config/someConfig";
import { onUserLeave } from "./servers/connector/handler/main";

app.appName = "chat demo"
app.setConfig("connector", { "connector": connector.Ws, "heartbeat": 20, "clientOffCb": onUserLeave, "interval": 50 });  // 注意： unity改为connectorTcp， creator改为connectorWs
app.setConfig("encodeDecode", { "msgDecode": msgDecode, "msgEncode": msgEncode });
app.setConfig("rpc", { "interval": 30 });
app.setConfig("logger", function (level, info) {
    if (level !== "debug") {
        console.log(level, info)
    }
});
app.setConfig("mydogList", () => {
    let userNum = "--";
    if (app.serverType === e_svrType.connector) {
        userNum = app.clientNum.toString();
    } else if (app.serverType === e_svrType.chat) {
        userNum = app.get<RoomMgr>("roomMgr").getUserNum().toString();
    }
    return [{ "title": "cpu(%)", "value": getCpuUsage() }, { "title": "userNum", "value": userNum }];
});

//初始化mysql，每个服一个
function initMysql(vApp: Application){
    //vApp.set("sqliteClient", new SqliteClient(vApp));
}

app.configure(e_svrType.gate, () => {
    app.set("hallMgr", new HallMgr(app));
});
app.configure(e_svrType.connector, () => {
    app.route(e_svrType.chat, (session: Session) => {
        return session.get("svr");
    });
});
app.configure(e_svrType.chat, () => {
    app.set("roomMgr", new RoomMgr(app));
});

app.configure(e_svrType.logic, () => {
    initMysql(app);
});

app.start();

process.on("uncaughtException", function (err: any) {
    console.log(err)
});

/*
sql.query("select id,password from account where username = ? limit 1", ["name"],
(err: any, users: { "id": number, "password": string }[]) => {
        if (err) {
            console.error("sql err:" + err);
        }
    }
);
*/

function msgDecode(cmdId: number, msgBuf: Buffer) {
    let msgStr = msgBuf.toString();
    console.log("↑ ", app.routeConfig[cmdId], msgStr);
    return JSON.parse(msgStr);
}

function msgEncode(cmdId: number, msg: any): Buffer {
    let msgStr = JSON.stringify(msg);
    console.log(" ↓", app.routeConfig[cmdId], msgStr);
    return Buffer.from(msgStr);
}
